package com.library.bookClass.dao;

import com.framework.BaseDao;
import com.framework.Page;
import com.library.entity.BookClass;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Repository
public class BookClassDaoImpl extends BaseDao<BookClass, Integer> {

	public void saveBookClass(BookClass bc){

		try {
			this.save(bc);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	public BookClass getBookClass(int bookClassId){
		try {
			BookClass bc=this.get(bookClassId);
			return bc;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public void updateBookClass(BookClass bc){
		try {
			this.update(bc);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void deleteBookClass(BookClass bc){
		try {
			this.delete(bc);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public List<BookClass> getAll(){
		try{
			return super.findByProperty("from BookClass", new Object[]{});
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	/*分页*/
	public Page<BookClass> findBookClassPage(int pageNum, int pageSize,Map paramsMap){
		int i = 0;
		int j = 0;
		String key;
		StringBuilder hql = new StringBuilder("from BookClass bc");
		List<Object> params = new ArrayList();

		if(paramsMap.size() != 0){
			Iterator<String> it = paramsMap.keySet().iterator();
			hql.append(" where ");
			while (it.hasNext()) {
				key = it.next();
				params.add(paramsMap.get(key));

				if(j != 0){
					if(params.get(i) != null)
						hql.append(" and bc."+ key + "=?");
					else{
						hql.append(" and bc."+ key + " is null");
						params.remove(i);
						++j;
						continue;
					}
				} else{
					if(params.get(i) != null)
						hql.append(" bc."+ key + "=?");
					else{
						hql.append(" bc."+ key + " is null");
						params.remove(i);
						++j;
						continue;
					}
				}
				++i;
				++j;
			}
		}
		try{
			return super.findByPage(pageNum,pageSize,hql.toString(),params.toArray());
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
